package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.query.QueryObject;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;


    // 提供一个方法处理查询所有部门数据请求，响应 HTML
    @RequestMapping("/list")
	@RequiresPermissions(value = {"role:list","角色列表"},logical = Logical.OR)
    public String list(Model model, @ModelAttribute("qo") QueryObject qo){
		PageInfo pageInfo = roleService.queryForList(qo);
		model.addAttribute("result", pageInfo);
        return "role/list"; // /WEB-INF/views/role/list.ftl
    }
    @RequestMapping("/input")
	@RequiresPermissions(value = {"role:input","角色编辑"},logical = Logical.OR)
    public String input(Long id, Model model){
		List<Permission> permissions = permissionService.listAll();
		model.addAttribute("permissions", permissions);
        if(id != null){ // 点击了修改按钮过来
            Role role = roleService.get(id);
            model.addAttribute("role", role);
        }
        return "role/input"; // /WEB-INF/views/role/input.ftl
    }

	@RequestMapping("/saveOrUpdate")
	@RequiresPermissions(value = {"role:saveOrUpdate","角色保存或更新"},logical = Logical.OR)
	public String saveOrUpdate(Role role, Long[] ids) {
		roleService.saveOrUpdate(role, ids);
		return "redirect:/role/list.do";
	}

    @RequestMapping("/delete")
	@RequiresPermissions(value = {"role:delete","角色删除"},logical = Logical.OR)
    public String delete(Long id){
        if (id != null) {
            roleService.delete(id);
        }
        return "redirect:/role/list.do";  // http://localhost/role/list.do
    }
}
